#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include "assembler.h"
#include "cutter.h"
#include "vertex_processor.h"
#include "clip.h"

struct INTERNAL_VERTEX primitives[3];
char occupied[3];

int mode = SQS_NONE;

void sqsPrimitiveAssembler(struct INTERNAL_VERTEX v) {
    sqsSetClipCode(&v);
    if (mode == SQS_POINTS) {
        sqsClipPoint(v);
    } else if (mode == SQS_LINES) {
        if (!occupied[0]) {
            primitives[0] = v;
            occupied[0] = (char) 1;
        } else {
            primitives[1] = v;
            sqsClipLine(primitives[0], primitives[1]);
            occupied[0] = (char) 0;
        }
    } else if (mode == SQS_TRIANGLE) {
        if (!occupied[0]) {
            primitives[0] = v;
            occupied[0] = (char) 1;
        } else if (!occupied[1]) {
            primitives[1] = v;
            occupied[1] = (char) 1;
        } else {
            primitives[2] = v;
            sqsClipTriangle(primitives[0], primitives[1], primitives[2]);
            occupied[0] = (char) 0;
            occupied[1] = (char) 0;
        }
    } else if (mode == SQS_LINE_STRIP) {
        if (!occupied[0]) {
            primitives[0] = v;
            occupied[0] = (char) 1;
        } else {
            primitives[1] = v;
            sqsClipLine(primitives[0], primitives[1]);
            primitives[0] = v;
        }
    } else if (mode == SQS_TRIANGLE_STRIP) {
        if (!occupied[0]) {
            primitives[0] = v;
            occupied[0] = (char) 1;
        } else if (!occupied[1]) {
            primitives[1] = v;
            occupied[1] = (char) 1;
        } else {
            primitives[2] = v;
            sqsClipTriangle(primitives[0], primitives[1], primitives[2]);
            primitives[0] = primitives[1];
            primitives[1] = primitives[2];
        }
    } else if (mode == SQS_TRIANGLE_FAN) {
        if (!occupied[0]) {
            primitives[0] = v;
            occupied[0] = (char) 1;
        } else if (!occupied[1]) {
            primitives[1] = v;
            occupied[1] = (char) 1;
        } else {
            primitives[2] = v;
            sqsClipTriangle(primitives[0], primitives[1], primitives[2]);
            primitives[1] = primitives[2];
        }
    }
}

void sqsAssemblyMode(int _mode) {
    mode = _mode;
    occupied[0] = (char) 0;
    occupied[1] = (char) 0;
    occupied[2] = (char) 0;
}
